import { getToken } from '@/utils/storage';

// 存放用户信息
const initialState = {
  profile: {} as ProFileType,
  auth: getToken(),
  user: {} as UserInfo,
  // auth: {
  //   token: '',
  //   refresh_token: '',
  // },
};

// 定义profile类型
export type ProFileType = {
  id: string;
  birthday: string;
  gender: number;
  mobile: string;
  name: string;
  photo: string;

  // 简介
  intro: string;
};

// 定义user类型
type UserInfo = {
  id: string;
  name: string;
  photo: string;
  art_count: number;
  follow_count: number;
  fans_count: number;
  like_count: number;
};

export type AuthType = {
  token: string;
  refresh_token: string;
};

// 定义一个action类型
type UserAction =
  | { type: 'user/saveAuth'; payload: AuthType }
  | { type: 'user/saveUseInfo'; payload: UserInfo }
  | { type: 'user/saveProfile'; payload: ProFileType }
  // 定义更新的action,Partial(泛型工具)把类型都变成可选的
  | { type: 'user/updateProfile'; payload: Partial<ProFileType> };

export default function userReducer(
  state = initialState,
  action: UserAction
): typeof initialState {
  switch (action.type) {
    case 'user/saveAuth':
      return {
        ...state,
        auth: action.payload,
      };
    case 'user/saveUseInfo':
      return {
        ...state,
        user: { ...action.payload },
      };
    // 编写保存数据的逻辑分支
    case 'user/saveProfile':
      return {
        ...state,
        profile: { ...action.payload },
      };
    // 编写更新逻辑
    case 'user/updateProfile':
      return {
        ...state,
        profile: {
          ...state.profile,
          ...action.payload,
        },
      };

    default:
      return state;
  }
}
